import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import RNFS, { DownloadFileOptions } from 'react-native-fs';
import StorageUtil from '../utils/StorageUtil';
import store from '../redux/store';

interface DownloadProgress {
  bytesWritten: number;
  contentLength: number;
  progress: number;
}

interface UploadOptions {
  file: any;
  data?: Record<string, any>;
  fileKey?: string;
  onProgress?: (progressEvent: any) => void;
}

interface DownloadResult {
  statusCode: number;
  bytesWritten: number;
  path: string;
}

class HttpClient {
  private instance: AxiosInstance;
  private baseURL: string;
  private timeout: number;
  
  constructor() {
    // "http://10.0.0.6:8000/index.php";
    this.baseURL = "http://10.0.0.6:8000/index.php";
    // this.baseURL = "http://111.229.85.199:9003/index.php"; // 替换为您的API域名
    this.timeout = 10000; // 10秒超时
    this.instance = axios.create({
      baseURL: this.baseURL,
      timeout: this.timeout,
      headers: {
        'Content-Type': 'application/json',
      }
    });

    this.setupInterceptors();
  }

  private setupInterceptors(): void {
    // 请求拦截器
    this.instance.interceptors.request.use(
      async (config) => {
        // user_token
        const token = await StorageUtil.getItem('user_token');
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
        // 可以统一处理响应数据
        if (response.data?.code === -1) {
          StorageUtil.removeItem('user_token');
          store.dispatch({
            type: 'SET_LOGIN',
            isLogin: false
          });
          return Promise.reject(new Error('Unauthorized'));
        }
        return response.data;
      },
      (error) => {
        // 统一错误处理
        if (error.response) {
          switch (error.response.status) {
            case 401:
              // 处理未授权
              break;
            case 403:
              // 处理禁止访问
              break;
            case 404:
              // 处理未找到
              break;
            case 500:
              // 处理服务器错误
              break;
          }
        }
        return Promise.reject(error);
      }
    );
  }

  // GET 请求
  public async get<T>(url: string, params?: any): Promise<T> {
    try {
      const response = await this.instance.get(url, { params });
      return response as T;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  // POST 请求
  public async post<T>(url: string, data?: any): Promise<T> {
    try {
      const response = await this.instance.post(url, data);
      return response as T;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  // 文件上传
  public async upload<T>(
    url: string,
    options: UploadOptions
  ): Promise<T> {
    try {
      const formData = new FormData();
      const fileKey = options.fileKey || 'file';
      
      // 添加文件
      formData.append(fileKey, {
        uri: options.file.uri,
        type: options.file.type || 'application/octet-stream',
        name: options.file.name || 'file'
      } as any);
      
      // 添加其他参数
      if (options.data) {
        Object.keys(options.data).forEach(key => {
          // 如果值是对象或数组，转换为 JSON 字符串
          const value = options.data && typeof options.data[key] === 'object'
            ? JSON.stringify(options.data[key]) 
            : options.data?.[key];
          formData.append(key, value);
        });
      }

      const config: AxiosRequestConfig = {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: options.onProgress,
      };

      const response = await this.instance.post(url, formData, config);
      return response as T;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  /**
   * 文件下载方法
   * @param url 下载地址
   * @param destinationPath 保存路径
   * @param progressCallback 进度回调
   * @param resumable 是否支持断点续传
   */
  public async download(
    url: string,
    destinationPath: string,
    progressCallback?: (progress: DownloadProgress) => void,
    resumable: boolean = true
  ): Promise<DownloadResult> {
    console.log('url is ' + url, 'destination path is ' + destinationPath);
    try {
      // 检查文件是否已存在（断点续传）
      let currentBytes = 0;
      if (resumable && await RNFS.exists(destinationPath)) {
        const stat = await RNFS.stat(destinationPath);
        currentBytes = stat.size;
      }

      // 获取文件总大小
      const headResponse = await axios.head(url);
      const totalBytes = parseInt(headResponse.headers['content-length'] || '0', 10);

      // 如果文件已完整下载，直接返回
      if (currentBytes === totalBytes && totalBytes > 0) {
        return {
          statusCode: 200,
          bytesWritten: totalBytes,
          path: destinationPath
        };
      }

      // 设置下载选项
      const downloadOptions: DownloadFileOptions = {
        fromUrl: url,
        toFile: destinationPath,
        headers: resumable && currentBytes > 0 ? {
          'Range': `bytes=${currentBytes}-`
        } : {},
        begin: (res: any) => {
          console.log('Download started:', res);
        },
        progress: (res: any) => {
          const progress = totalBytes > 0 ? (currentBytes + res.bytesWritten) / totalBytes : 0;
          
          progressCallback?.({
            bytesWritten: currentBytes + res.bytesWritten,
            contentLength: totalBytes,
            progress
          });
        },
        backgroundTimeout: 30000 // 后台下载超时时间
      };

      // 开始下载
      const response = await RNFS.downloadFile(downloadOptions).promise;

      // 验证下载结果
      if (response.statusCode !== 200 && response.statusCode !== 206) {
        throw new Error(`Download failed with status code: ${response.statusCode}`);
      }

      return {
        statusCode: response.statusCode,
        bytesWritten: response.bytesWritten,
        path: destinationPath
      };

    } catch (error) {
      // 如果下载失败且文件存在，则删除可能损坏的文件
      if (await RNFS.exists(destinationPath)) {
        await RNFS.unlink(destinationPath);
      }
      throw this.handleError(error);
    }
  }

  // /**
  //  * 取消下载
  //  * @param path 下载文件路径
  //  */
  // public async cancelDownload(path: string): Promise<void> {
  //   try {
  //     RNFS.stopDownload(path);
  //     if (await RNFS.exists(path)) {
  //       await RNFS.unlink(path);
  //     }
  //   } catch (error) {
  //     throw this.handleError(error);
  //   }
  // }

  // 错误处理
  private handleError(error: any): Error {
    if (error.response) {
      // 服务器返回错误状态码
      const message = error.response.data?.message || '请求失败';
      return new Error(message);
    } else if (error.request) {
      // 请求发送成功但没有收到响应
      return new Error('网络错误，请检查您的网络连接');
    } else {
      // 请求配置出错
      return new Error('请求配置错误');
    }
  }
}

// 导出单例实例
export const HTTP = new HttpClient();
export default HTTP;